package com.example.streamapi.controller;

import com.example.streamapi.service.OllamaService;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

@RestController
@RequestMapping("/api")
public class ChatController {
    private final OllamaService ollamaService;

    public ChatController(OllamaService ollamaService) {
        this.ollamaService = ollamaService;
    }

    @PostMapping(value = "/chat")
    public String chat() {
        System.out.println("chat called ");
        return "123";
    }

    @PostMapping(value = "/stream_chat", produces = MediaType.APPLICATION_NDJSON_VALUE)
    public Flux<String> streamChat(@RequestBody ChatRequest request) {
        System.out.println("Request received: " + request);
        if (request.getContent() == null || request.getContent().isEmpty()) {
            throw new IllegalArgumentException("Content is required");
        }
        return ollamaService.streamChat(request.getContent())
                .map(response -> {
                    System.out.println("Response received: " + response);// 处理特殊字符：将换行符、回车符、制表符等转换为它们的转义表示
                    String escapedResponse = response
                            .replace("\n", "\\n")
                            .replace("\r", "\\r")
                            .replace("\t", "\\t")
                            .replace("\"", "\\\"");
                    return String.format("{\"response\": \"%s\"}\n", escapedResponse);
                });
    }

}

@Data
@AllArgsConstructor
@NoArgsConstructor
class ChatRequest {
    private String content;
}